<template>
  <div>
    <div class="header">
      <span style="margin-left: 20px">关键字</span>
      <el-input placeholder="请输入关键字" v-model="empReq.keyword" style="width: 200px; margin-left: 10px"
        clearable></el-input>
      <el-button type="primary" style="margin-left: 20px" size="small" @click="
        empReq.pageIndex = 1
      getEmployees()
        ">
        关键字搜索
      </el-button>
      <el-button type="success" style="margin-left: 20px" size="small" @click="
        newEmployee = {}
      addEmployeeVis = true
        ">
        添加
      </el-button>
    </div>
    <el-table style="overflow: auto" :data="empRes.Items" stripe border highlight-current-row>
      <el-table-column type="index" width="40"></el-table-column>
      <el-table-column label="ID" prop="ECV_TargetID" width="40"></el-table-column>
      <el-table-column label="姓名" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.EMP_StatusDesc" :type="scope.row.EMP_Status != 1 ? 'danger' : 'primary'">
            {{ scope.row.EMP_StatusDesc }}
          </el-tag>
          {{ scope.row.USR_Name }}
        </template>
      </el-table-column>
      <el-table-column label="性别" prop="USR_SexDesc" width="60"></el-table-column>
      <el-table-column label="手机号码" prop="USR_Phone" width="140"></el-table-column>
      <!-- <el-table-column
        label="邮箱"
        prop="USR_Email"
        width="160"
      ></el-table-column> -->
      <el-table-column label="角色">
        <template slot-scope="scope">
          <el-tag v-for="item in scope.row.Roles" :key="item.RE_ID">
            {{ item.RL_Name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="300">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="
            chooseEmployee = scope.row
          editEmployeeVis = true
            " icon="el-icon-edit">
            修改/完善
          </el-button>
          <el-button type="text" icon="el-icon-connection" @click="
            chooseEmployee = scope.row
          combineVis = true
            ">
            合并
          </el-button>
          <el-button type="text" size="small" icon="el-icon-warning" @click="freezeUser(scope.row.ECV_TargetID)"
            v-if="scope.row.EMP_Status == 1">
            注销
          </el-button>
          <el-button type="text" size="small" icon="el-icon-warning" @click="unFreezeUser(scope.row.ECV_TargetID)"
            v-if="scope.row.EMP_Status == 0">
            启用
          </el-button>
          <el-button type="text" size="small" icon="el-icon-delete" @click="deleteUser(scope.row.ECV_TargetID)">
            删除
          </el-button>
          <el-button type="text" size="small" @click="
            chooseEmployee = scope.row
          editEmplayeeRateVis = true
            " icon="el-icon-edit">
            提成率配置
          </el-button>
          <el-button type="text" size="small" icon="el-icon-menu" @click="toForm(scope.row.EMP_FormID)"
            v-if="scope.row.EMP_FormID">
            来源
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="width: 100%; height: 40px">
      <el-pagination layout="total,prev,pager,next,sizes" style="float: right" background
        :current-page.sync="empReq.pageIndex" :total="empRes.Total" :page-size="empReq.pageSize"
        :page-sizes="[10, 15, 20]" @size-change="
          (val) => {
            empReq.pageSize = val
            getEmployees()
          }
        " @current-change="getEmployees()"></el-pagination>
    </div>
    <el-drawer title="添加用户" :visible.sync="addEmployeeVis" direction="rtl">
      <el-form label-width="100px" style="margin-top: 20px; width: 80%" v-if="newEmployee">
        <el-form-item label="姓名">
          <el-input v-model="newEmployee.USR_Name"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select filterable v-model="newEmployee.USR_Sex" style="width: 100%">
            <el-option v-for="item in sexes" :key="item.val" :label="item.label" :value="item.val"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="newEmployee.USR_Phone"></el-input>
        </el-form-item>
        <el-form-item label="联系地址">
          <el-input v-model="newEmployee.USR_Address"></el-input>
        </el-form-item>
        <el-form-item label="身份证">
          <el-input v-model="newEmployee.USR_IDCard"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="newEmployee.USR_Email"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="newEmployee.EMP_Remark"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <div v-for="item in roles" :key="item.RL_ID">
            <el-checkbox @change="
              (ischecked) => {
                empRoleChange(newEmployee, item, ischecked)
              }
            ">
              {{ item.RL_Name }}
            </el-checkbox>
          </div>
        </el-form-item>
        <el-form-item label="报销限制月数" style="margin-left: 20px">
          <el-input-number v-model="newEmployee.EMP_ExpenseLimitMonth" :min="0" :max="100"
            label="请输入报销限制月数"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="addEmployee()">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <el-drawer title="编辑用户" :visible.sync="editEmployeeVis" direction="rtl">
      <el-form label-width="100px" style="margin-top: 20px; width: 80%" :model="chooseEmployee" v-if="chooseEmployee"
        ref="chooseEmployee">
        <el-form-item label="姓名" prop="USR_Name" :rules="[{ required: true, message: '请填写姓名' }]">
          <el-input v-model="chooseEmployee.USR_Name"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="USR_Phone" :rules="[{ required: true, message: '请填写手机号码' }]">
          <el-input v-model="chooseEmployee.USR_Phone"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select filterable v-model="chooseEmployee.USR_Sex" style="width: 100%">
            <el-option v-for="item in sexes" :key="item.val" :label="item.label" :value="item.val"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系地址">
          <el-input v-model="chooseEmployee.USR_Address"></el-input>
        </el-form-item>
        <el-form-item label="身份证">
          <el-input v-model="chooseEmployee.USR_IDCard"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="chooseEmployee.USR_Email"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="chooseEmployee.EMP_Remark"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <div v-for="item in roles" :key="item.RL_ID">
            <el-checkbox :value="chooseEmployee.Roles.findIndex(
              (x) => x.RE_RoleID == item.RL_ID
            ) != -1
              " @change="
                (ischecked) => {
                  empRoleChange(chooseEmployee, item, ischecked)
                }
              ">
              {{ item.RL_Name }}
            </el-checkbox>
          </div>
        </el-form-item>
        <el-form-item label="报销限制月数" style="margin-left: 20px">
          <el-input-number v-model="chooseEmployee.EMP_ExpenseLimitMonth" :min="0" :max="100"
            label="请输入报销限制月数"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button @click="editEmployee" size="medium" type="primary" icon="el-icon-circle-check" title="保存">
            保存
          </el-button>
          <el-button @click="chooseEmployeeVis = false" size="medium" title="取消">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <el-dialog :visible.sync="combineVis" title="员工信息合并" width="500px">
      <el-form label-width="80px" v-if="chooseEmployee">
        <el-form-item label="原员工" type="textarea" :rows="3">
          <el-input v-model="chooseEmployee.USR_Name" disabled></el-input>
        </el-form-item>
        <el-form-item label="合并至">
          <el-select style="width: 350px" filterable remote reserve-keyword v-model="combineReq.targetId">
            <el-option v-for="item in combineEmps" :key="item.ECV_TargetID" :label="item.USR_Name"
              :value="item.ECV_TargetID">
              【{{ item.USR_Name }}】{{ item.USR_Phone | encodePhone }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" type="textarea" :rows="3">
          <el-input v-model="combineReq.remark" type="textarea" :rows="3" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="combineEmployee" type="text" icon="el-icon-connection" title="合并">
            合并
          </el-button>
          <el-button @click="combineVis = false" type="text" title="取消">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="提成率修改" :visible.sync="editEmplayeeRateVis" width="400px" :modal-append-to-body="false" center>
      <editEmplayeeRate v-if="chooseEmployee" :empId="chooseEmployee.ECV_TargetID" @saved="editEmplayeeRateVis = false"
        @canceled="editEmplayeeRateVis = false" />
    </el-dialog>
  </div>
</template>
<script>
import {
  getRoles,
  getEmployees,
  getUsingEmployees,
  addEmployee,
  deleteEmployee,
  freezeEmployee,
  unfreezeEmployee,
  editEmployee,
  combineEmployee,
} from '@/api/flowCenter/organiztion/employeeManage'
import editEmplayeeRate from '@/views/web/orgnization/components/editEmplayeeRate.vue'
export default {
  components: { editEmplayeeRate },
  data: function () {
    return {
      keyword: '',
      sexes: [
        { val: 1, label: '男' },
        { val: 0, label: '女' },
      ],
      emps: [],
      roles: [],
      posts: [],
      empReq: {
        pageIndex: 1,
        pageSize: 10,
        keyword: null,
      },
      empRes: {
        Items: [],
        Total: 0,
      },
      combineReq: {
        sourceId: null,
        targetId: null,
        remark: null,
      },
      newEmployee: {},
      chooseEmployee: null,
      addEmployeeVis: false,
      editEmployeeVis: false,
      combineVis: false,
      editEmplayeeRateVis: false,
    }
  },
  computed: {
    combineEmps() {
      return this.emps.filter(
        (x) => x.ECV_TargetID != this.chooseEmployee.ECV_TargetID
      )
    },
  },
  methods: {
    toForm(formId) {
      this.$router.push({
        name: 'formInfoPage',
        query: { formId },
      })
    },
    empRoleChange(emp, role, ischecked) {
      if (ischecked) {
        if (!emp.Roles) emp.Roles = []
        emp.Roles.push({
          RE_EmployeeId: emp.ECV_TargetID,
          RE_RoleID: role.RL_ID,
        })
      } else
        emp.Roles.splice(
          emp.Roles.findIndex((x) => x.RE_RoleID == role.RL_ID),
          1
        )
    },
    addEmployee() {
      addEmployee(this.newEmployee).then((r) => {
        this.getEmployees()
        this.newEmployee = {}
        this.addEmployeeVis = false
      })
    },
    combineEmployee() {
      if (!this.chooseEmployee) {
        return
      }
      this.combineReq.sourceId = this.chooseEmployee.ECV_TargetID
      this.$confirm(
        `是否将${this.chooseEmployee.USR_Name}合并到该员工中？信息合并后，原员工相关的各种信息（如案件、日志、票据等）都会合并到新员工中，请谨慎操作`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info',
        }
      )
        .then(() => {
          combineEmployee(this.combineReq).then(({ data }) => {
            this.getEmployees()
            this.combineVis = false
          })
        })
        .catch(() => {
          return
        })
    },
    editEmployee() {
      if (!this.chooseEmployee) {
        return
      }
      this.$confirm(`是否保存？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      })
        .then(() => {
          editEmployee(this.chooseEmployee).then(() => {
            this.getEmployees()
            this.editEmployeeVis = false
          })
        })
        .catch(() => {
          return
        })
    },
    freezeUser(id) {
      this.$confirm(`是否注销用户？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        freezeEmployee(id).then((r) => {
          this.getEmployees()
          this.addEmployeeVis = false
          this.newEmployee = {}
        })
      })
    },
    unFreezeUser(id) {
      this.$confirm(`是否解冻用户？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        unfreezeEmployee(id).then((r) => {
          this.getEmployees()
        })
      })
    },
    deleteUser(id) {
      this.$confirm(`是否删除用户？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteEmployee(id).then((r) => {
          this.getEmployees()
        })
      })
    },
    getEmployees: function () {
      getEmployees(this.empReq).then(({ data }) => (this.empRes = data))
    },
    getUsingEmployees: function () {
      getUsingEmployees().then(({ data }) => (this.emps = data))
    },
    getRoles: function () {
      getRoles().then(({ data }) => (this.roles = data))
    },
  },
  created: function () {
    var data = this.$store.getters['pagination/getRoutePage'](this.$route)
    Object.assign(this.$data, data)
    this.getEmployees()
    this.getUsingEmployees()
    this.getRoles()
  },
  beforeRouteLeave(to, from, next) {
    this.$store.dispatch('pagination/setRoutePage', {
      route: this.$route,
      pageData: this.$data,
    })
    next()
  },
}
</script>
<style>
.el-drawer.rtl {
  overflow: scroll;
}
</style>
<style scoped>
.header {
  width: 100%;
  padding-top: 10px;
  padding-bottom: 10px;
  height: auto;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  background: #ffffff;
  border-radius: 5px;
  border-bottom: #f4f8ff 2px solid;
  display: flex;
  margin-bottom: 11px;
  align-items: center;
}
</style>
